package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.BusinessException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang.StringUtils;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService service;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private UserService userService;

    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders) {
        //获得当前用户id
        Long currentId = BaseContext.getCurrentId();
        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, currentId);
        List<ShoppingCart> list = shoppingCartService.list(wrapper);
        if (list == null || list.size() == 0) {
            throw new BusinessException("购物车不能为空");
        }
        //查询用户数据
        User user = userService.getById(currentId);
        Long userId = user.getId();
        //查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null) {
            throw new BusinessException("用户地址信息有误，不能下单");
        }
        //获取订单号
        Long ordersId = IdWorker.getId();
        //总价
        AtomicInteger amount = new AtomicInteger(0);
        //组装订单明细信息，信息来源于购物车
        List<OrderDetail> orderDetailList = list.stream().map((shoppingCart) -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(ordersId);
            //一条订单明细中的总金额
            amount.addAndGet(orderDetail.getAmount().multiply(new BigDecimal(orderDetail.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        // 组装订单数据
        //订单Id
        orders.setId(ordersId);
        //订单创建时间
        orders.setOrderTime(LocalDateTime.now());
        //订单结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //订单状态  1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setStatus(2);
        //总金额
        orders.setAmount(new BigDecimal(amount.get()));
        //设置用户id
        orders.setUserId(userId);
        //订单号
        orders.setNumber(String.valueOf(ordersId));
        //用户名
        orders.setUserName(user.getName());
        //收货人
        orders.setConsignee(addressBook.getConsignee());
        //收货人联系电话
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表插入一条订单数据
        service.save(orders);
        //向订单明细表中插入数据
        orderDetailService.saveBatch(orderDetailList);
        //清空购物车数据
        shoppingCartService.remove(wrapper);
        return R.success("下单成功");
    }

    @GetMapping("/userPage")
    public R queryOrders(Integer page, Integer pageSize) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        wrapper.orderByDesc(Orders::getOrderTime);
        service.page(ordersPage, wrapper);
        long total = ordersPage.getTotal();

        List<Orders> records = ordersPage.getRecords();
        List<OrdersDto> ordersDtos = new ArrayList<>();
        for (Orders order : records) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(order, ordersDto);

            Long orderId = order.getId();
            Orders byId = service.getById(orderId);
            //获取订单号
            String number = byId.getNumber();
            LambdaQueryWrapper<OrderDetail> qw = new LambdaQueryWrapper<>();
            qw.eq(OrderDetail::getOrderId, number);
            List<OrderDetail> orderDetails = orderDetailService.list(qw);
            int num = 0;
            for (OrderDetail orderDetail : orderDetails) {
                num += orderDetail.getNumber().intValue();
            }
            ordersDto.setSumNum(num);
            ordersDto.setOrderDetails(orderDetails);
            ordersDtos.add(ordersDto);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("pages", (int) total);
        map.put("records", ordersDtos);
        return R.success(map);
    }

    @PostMapping("again")
    public R orderAgain(Integer id) {
        //获取再来一单所对应的订单
        Orders byId = service.getById(id);
        //设置新的订单id
        long id1 = IdWorker.getId();
        byId.setId(id1);
        //设置新的订单号码
        String number = String.valueOf(IdWorker.getId());
        byId.setNumber(number);
        //设置下单时间
        byId.setOrderTime(LocalDateTime.now());
        //设置结账时间
        byId.setCheckoutTime(LocalDateTime.now());
        byId.setStatus(2);
        //向订单表中插入一条数据
        service.save(byId);
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDetail::getOrderId, id);
        List<OrderDetail> list = orderDetailService.list(wrapper);
        list = list.stream().map((orderDetail) -> {
            //设置订单明细表id
            long id2 = IdWorker.getId();
            //设置订单号码
            orderDetail.setOrderId(id1);
            //设置订单明细id
            orderDetail.setId(id2);
            return orderDetail;
        }).collect(Collectors.toList());
        //向订单明细表中插入多条数据
        orderDetailService.saveBatch(list);
        return R.success("再来一单");
    }
    //管理端查询订单明细
    @GetMapping("/page")
    public R page(int page, int pageSize, String number, String beginTime, String endTime) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        //根据number进行模糊查询
        wrapper.like(!StringUtils.isEmpty(number),Orders::getNumber, number);
        //根据Datetime进行时间范围查询
        if(beginTime != null && endTime != null){
            wrapper.ge(Orders::getOrderTime,beginTime);
            wrapper.le(Orders::getCheckoutTime,endTime);
        }
        wrapper.orderByDesc(Orders::getOrderTime);
        //进行分页查询
      service.page(pageInfo, wrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,ordersDtoPage,"records");
        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> list = records.stream().map((order) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(order, ordersDto);
            String name = "用户" + order.getUserId();
            ordersDto.setUserName(name);
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(list);

        return R.success(ordersDtoPage);
    }
    //外卖订单派送
    @PutMapping
    public R send(@RequestBody Orders orders){
        Long ordersId = orders.getId();
        Integer status = orders.getStatus();
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getId,ordersId);
        Orders one = service.getOne(wrapper);
        one.setStatus(status);
        service.updateById(one);
        return R.success("派送成功") ;
    }

}
